package com.zgc.simpleholiday.service;

import com.google.gson.Gson;
import com.zgc.simpleholiday.model.DayStatus;
import com.zgc.simpleholiday.model.HolidayItem;
import com.zgc.simpleholiday.model.Holidays;
import com.zgc.simpleholiday.utils.FilePathUtil;
import com.zgc.simpleholiday.utils.HolidayUtil;
import com.zgc.simpleholiday.utils.SerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class HolidayService {

    private static final Logger log = LoggerFactory.getLogger(HolidayService.class);
    private static final List<String> WEEKEND_LIST = Arrays.asList("六", "日");

    public DayStatus getHoliday(String year, String month, String day) {
        String thisDay = day.replaceFirst("^0", "");
        String thisMonth = month.replaceFirst("^0", "");
        return Objects.requireNonNull(getHolidayByMonth(year, month).stream().filter(item -> item.getMonth().equals(thisMonth) && item.getDay().equals(thisDay)).findFirst().orElse(null)).getStatus();
    }

    public List<HolidayItem> getHolidayByMonth(String year, String month) {

        String filePath;
        try {
            filePath = FilePathUtil.getFilePath2(year + "-" + month);
            log.info("get holidays from cache, {}-{}", year, month);
            if (new File(filePath).exists()) {
                return SerUtil.deserialization(filePath);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Gson gson = new Gson();
        Holidays holidays = gson.fromJson(HolidayUtil.getMonth(year, month), Holidays.class);
        if (!"0".equals(holidays.getStatus())) {
            throw new RuntimeException("get holidays failed");
        }
        List<HolidayItem> almanacList = holidays.getData().get(0).getAlmanac().stream()
                // status 1: 节假日 2: 补班  null:其他;
                // cnDay 周末: 周末 其他:工作日
                .peek(almanac -> almanac.setDayStatus("1".equals(almanac.getStatus()) ? DayStatus.HOLIDAY : "2".equals(almanac.getStatus())? DayStatus.EXTRA : WEEKEND_LIST.contains(almanac.getCnDay())?DayStatus.WEEKEND: DayStatus.WORKDAY))
                .map(HolidayItem::new)
                .toList();
        try {
            SerUtil.serialization(almanacList,filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("get holidays from api, {}-{}", year, month);
        return almanacList;
    }

}
